<?php
session_start();

require('settings.php');

if (!isset($_SESSION["cart"])) {
    $_SESSION["cart"] = array();
}

$mysqli = new mysqli('mysql.hostinger.es', 'u487121236_jaume', 'major1991', 'u487121236_asix');

if ($_POST) {
    $CLASS_APP = new app($mysqli);

    $function = $_POST["func"];

    switch ($function) {

        case 'addItem':
            $id = $_POST["item"];

            $item = $CLASS_APP->get_products_id($id);

            if (!array_key_exists($id, $_SESSION["cart"])) {
                $_SESSION["cart"][$id] = array("id" => $item["id_products"], "itemname" => $item["product"], "itemprice" => $item["price"], "itemqty" => 1);
            } else {
                $_SESSION["cart"][$id]["itemqty"] += 1;
            }

            $totalItems = get_cart_totalItems($_SESSION["cart"]);
            $totalPrice = get_cart_total($_SESSION["cart"]);

            $response = array(
                "added" => $_SESSION["cart"][$id],
                "cartItems" => $totalItems,
                "totalPrice" => $totalPrice
            );

            echo json_encode($response);

            break;

        case 'dcrcartItem':
            $id = $_POST["id"];

            if ($_SESSION["cart"][$id]["itemqty"] > 0) {
                $_SESSION["cart"][$id]["itemqty"] = --$_SESSION["cart"][$id]["itemqty"];

                if ($_SESSION["cart"][$id]["itemqty"] == 0)
                    unset($_SESSION["cart"][$id]);
            }


            $totalItems = get_cart_totalItems($_SESSION["cart"]);
            $totalPrice = get_cart_total($_SESSION["cart"]);
            $cart = generate_checkout_cart($_SESSION["cart"]);

            $response = array(
                "cart" => $cart,
                "cartItems" => $totalItems,
                "totalPrice" => $totalPrice
            );

            echo json_encode($response);

            break;

        case 'ncrcartItem':
            $id = $_POST["id"];

            $_SESSION["cart"][$id]["itemqty"] += 1;

            $totalItems = get_cart_totalItems($_SESSION["cart"]);
            $totalPrice = get_cart_total($_SESSION["cart"]);
            $cart = generate_checkout_cart($_SESSION["cart"]);

            $cart = "<tr><td></td><td>Pid</td><td>Product name</td><td>Price per unit</td><td>Qty</td><td>Price</td></tr>";

            foreach ($_SESSION["cart"] as $cart_item) {
                $cart .= "<tr id='#item'><td><a href='javascript: removeItem(" . $cart_item["id"] . ")'><i class='icon-remove'></i></a></td><td>" . $cart_item["id"] . "</td><td><a href='product-detail.php?id={$cart_item['id']}'>" . $cart_item["itemname"] . "</a></td><td>" . $cart_item["itemprice"] . " €</td><td><button onclick='dcrcartItem({$cart_item['id']})' class='btn_qty'> - </button>" . $cart_item["itemqty"] . "<button onclick='ncrcartItem({$cart_item['id']})' class='btn_qty'> + </button></td><td>" . $cart_item["itemprice"] * $cart_item["itemqty"] . " €</td></tr>";
            }

            $response = array(
                "cart" => $cart,
                "cartItems" => $totalItems,
                "totalPrice" => $totalPrice
            );

            echo json_encode($response);

            break;

        case 'removeItem':
            $id = $_POST["id"];

            unset($_SESSION["cart"][$id]);

            $totalItems = get_cart_totalItems($_SESSION["cart"]);
            $totalPrice = get_cart_total($_SESSION["cart"]);
            $cart = generate_checkout_cart($_SESSION["cart"]);

            $response = array(
                "cart" => $cart,
                "cartItems" => $totalItems,
                "totalPrice" => $totalPrice
            );

            echo json_encode($response);

            break;


        case 'saveEmail':
            $email = $_POST["email"];

            $_SESSION["email"] = $email;

            $CLASS_APP = new app($mysqli);
            $paypal = new Paypal();

            $params = array(
                'RETURNURL' => $PayPalReturnURL,
                'CANCELURL' => $PayPalCancelURL,
            );

            $k = 0;
            foreach ($_SESSION["cart"] as $product) {
                $itemid = $product["id"];
                $itemqty = $product["itemqty"];
                $itemprice = $product["itemprice"];

                $params["L_PAYMENTREQUEST_0_NAME$k"] = $product["itemname"];
                $params["L_PAYMENTREQUEST_0_NUMBER$k"] = $itemid;
                $params["L_PAYMENTREQUEST_0_AMT$k"] = $itemprice;
                $params["L_PAYMENTREQUEST_0_QTY$k"] = $itemqty;

                $total += $itemprice * $itemqty;
                $k++;
            }

            $params["PAYMENTREQUEST_0_AMT"] = $total;
            $params["PAYMENTREQUEST_0_CURRENCYCODE"] = 'EUR';
            $params["NOSHIPPING"] = 1;

            $response = $paypal->request('SetExpressCheckout', $params);

            if ($response) {
                $paypalurl = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&useraction=commit&token=" . $response['TOKEN'];
            } else {
                $paypalurl = false;
            }

            sleep(1); //Stop the code 1 seconds to give time to the session to save before the page redirect us to paypal

            echo $paypalurl;

            break;

        case 'searchGame':
            $game = $_POST["game"];

            $query = $mysqli->query("select * from products where product LIKE '%$game%'");
            $results = "";

            while ($row = $query->fetch_assoc()) {
                $results .= "<div style='background: url(admin/uploads/images/" . $row['file'] . ") no-repeat;' class='item'>";
                $results .= "<div class='product-details'>";
                $results .= "<div class='title'>";
                $results .= "<a href='product-detail.php?id=" . $row["id_products"] . "'><h2>" . $row["product"] . "</h2></a>";
                $results .= "</div>";
                $results .= "<div class='price'>";
                $results .= "<strong>" . $row["price"] . " €</strong>";
                $results .= "<button onclick='addItem(" . $row["id_products"] . ")' class='btn_buy'>BUY</button></div></div></div>";
            }

            echo $results;

            break;

        case 'GetOrderDetails':
            $token = $_POST['token'];

            $paypal = new Paypal();

            $params = array(
                'TOKEN' => $token,
            );
            $response = $paypal->request('GetExpressCheckoutDetails', $params);

            sleep(1);

            echo json_encode($response);

            break;

        case 'DoPayment':
            $token = $_POST['token'];
            $payerid = $_POST['payerid'];
            $amt = $_POST['amt'];

            $paypal = new Paypal();

            $params = array(
                'TOKEN' => $token,
                'PAYERID' => $payerid,
                'PAYMENTREQUEST_0_AMT' => $amt,
                'PAYMENTREQUEST_0_CURRENCYCODE' => 'EUR'
            );

            $response = $paypal->request('DoExpressCheckoutPayment', $params);

            echo json_encode($response);

            break;

        case 'DeliverOrder':

            foreach ($_SESSION["cart"] as $cart_item) {

                $query = $mysqli->query("select product, product_key from products_keys pk inner join products p on pk.products=p.id_products where id_products = {$cart_item["id"]} and pk.used is null limit {$cart_item["itemqty"]}");
                while ($row = $query->fetch_assoc()) {
                    $item[$row["product"]][] = $row["product_key"];
                    $mysqli->query("UPDATE `products_keys` SET `used`=1 WHERE product_key='". $row["product_key"] ."'");
                }
            }

            $message = "Thank you for trusting us. You can now activate the game. <br><br>";

            foreach ($item as $product => $keys) {
                $message .= "<b>" . $product . "</b><br>";
                foreach ($keys as $key) {
                    $message .= "Key: " . $key . "<br>";
                }
            }
            $mail = $_SESSION["email"];

            $headers = "From: admin@jcardell-asix.com  \r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

            mail($mail, "Your order - jcardell-asix", $message, $headers);

            session_destroy();

            $totalItems = 0;
            $totalPrice = 0;

            $response = array(
                "order" => $item,
                "items" => $totalItems,
                "price" => $totalPrice,
                "email" => $mail
            );

            echo json_encode($response);

            break;
    }
}
?>